<!DOCTYPE html>
<!--
  The MIT License (MIT)

  Copyright (c) 2017 Tarek Sherif

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<html>
<head>
    <title>PicoGL.js: Deferred Rendering</title>
    <script src="utils/gl-matrix.js"></script>
    <script src="../build/picogl.js"></script>
    <script src="utils/utils.js"></script>
    <link rel="stylesheet" href="../site/css/picogl-example.css"> 
</head>
<body>
    <div id="example-title">
        PicoGL.js Example: Deferred Rendering
        <div>
            <a href="https://github.com/tsherif/picogl.js/blob/master/examples/deferred.html">Source code</a>
        </div>
    </div>
    <canvas id="gl-canvas"></canvas>
    <script id="geo-vs" type="x-vertex-shader">
        #version 300 es
        
        layout(location=0) in vec4 aPosition;
        layout(location=1) in vec3 aNormal;
        layout(location=2) in vec4 aUV;
        
        layout(std140) uniform BoxUniforms {
            mat4 uMVP;
            mat4 uModelMatrix;
        };
        
        out vec4 vPosition;
        out vec4 vNormal;
        out vec4 vUV;
        void main() {
            vPosition = uModelMatrix * aPosition;
            vNormal = uModelMatrix * vec4(aNormal, 0.0);
            vUV = aUV;
            gl_Position = uMVP * aPosition;
        }
    </script>
    <script id="geo-fs" type="x-fragment-shader">
        #version 300 es
        precision highp float;

        in vec4 vPosition;
        in vec4 vNormal;
        in vec4 vUV;

        layout(location=0) out vec4 position;
        layout(location=1) out vec4 normal;
        layout(location=3) out vec4 uv;
        void main() {
            position = vPosition;
            normal = vec4(normalize(vNormal.xyz), 0.0);
            uv = vUV;
        }
    </script> 
    <script id="main-vs" type="x-vertex-shader">
        #version 300 es
        
        layout(location=0) in vec4 aPosition;

        layout(std140) uniform LightUniforms {
            mat4 uMVP;
            vec4 uLightPosition;
            vec4 uLightColor;
        };

        void main() {
            gl_Position = uMVP * aPosition;
        }
    </script>
    <script id="main-fs" type="x-fragment-shader">
        #version 300 es
        precision highp float;

        layout(std140) uniform LightUniforms {
            mat4 uMVP;
            vec4 uLightPosition;
            vec4 uLightColor;
        };

        uniform vec3 uEyePosition;

        uniform sampler2D uPositionBuffer;
        uniform sampler2D uNormalBuffer;
        uniform sampler2D uUVBuffer;
        uniform sampler2D uTextureMap;

        out vec4 fragColor;
        void main() {
            ivec2 fragCoord = ivec2(gl_FragCoord.xy);
            vec3 position = texelFetch(uPositionBuffer, fragCoord, 0).xyz;
            vec3 normal = normalize(texelFetch(uNormalBuffer, fragCoord, 0).xyz);
            vec2 uv = texelFetch(uUVBuffer, fragCoord, 0).xy;

            vec4 baseColor = texture(uTextureMap, uv);


            vec3 eyeDirection = normalize(uEyePosition - position);
            vec3 lightVec = uLightPosition.xyz - position;
            float attenuation = 1.0 - length(lightVec);
            vec3 lightDirection = normalize(lightVec);
            vec3 reflectionDirection = reflect(-lightDirection, normal);
            float nDotL = max(dot(lightDirection, normal), 0.0);
            vec3 diffuse = nDotL * uLightColor.rgb;
            float ambient = 0.1;
            vec3 specular = pow(max(dot(reflectionDirection, eyeDirection), 0.0), 20.0) * uLightColor.rgb;

            fragColor = vec4(attenuation * (ambient + diffuse + specular) * baseColor.rgb, baseColor.a);
        }
    </script> 
    <script type="text/javascript">
        utils.addTimerElement();

        var canvas = document.getElementById("gl-canvas");

        if (!utils.testWebGL2()) {
            console.error("WebGL 2 not available");
            document.body.innerHTML = "This example requires WebGL 2 which is unavailable on this system."
        }

        if (!utils.testExtension("EXT_color_buffer_float")) {
            document.body.innerHTML = "This example requires extension EXT_color_buffer_float which is not supported on this system."
        }
        
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var app = PicoGL.createApp(canvas)
        .clearColor(0.0, 0.0, 0.0, 1.0)
        .depthTest()
        .depthFunc(PicoGL.LEQUAL)
        .blendFunc(PicoGL.ONE, PicoGL.ONE)
        .floatRenderTargets();

        var timer = app.createTimer();

        // SET UP GBUFFER PROGRAM
        var geoVsSource =  document.getElementById("geo-vs").text.trim();
        var geoFsSource =  document.getElementById("geo-fs").text.trim();
        var geoProgram = app.createProgram(geoVsSource, geoFsSource);

        var positionTarget = app.createTexture2D(app.width, app.height, { 
            type: PicoGL.FLOAT 
        });
        var normalTarget = app.createTexture2D(app.width, app.height, { 
            type: PicoGL.FLOAT 
        });
        var uvTarget = app.createTexture2D(app.width, app.height, { 
            type: PicoGL.FLOAT,
            format: PicoGL.RG
        });
        var depthTarget = app.createRenderbuffer(app.width, app.height, PicoGL.DEPTH_COMPONENT16);
        var gBuffer = app.createFramebuffer()
        .colorTarget(0, positionTarget)
        .colorTarget(1, normalTarget)
        .colorTarget(3, uvTarget)
        .depthTarget(depthTarget);
        console.assert(gBuffer.getStatus() === PicoGL.FRAMEBUFFER_COMPLETE, "G-buffer framebuffer is not complete!");

        // SET UP MAIN PROGRAM
        var vsSource =  document.getElementById("main-vs").text.trim();
        var fsSource =  document.getElementById("main-fs").text.trim();
        var mainProgram = app.createProgram(vsSource, fsSource);

        // GEOMETRY
        var box = utils.createBox();
        var positions = app.createVertexBuffer(PicoGL.FLOAT, 3, box.positions);
        var normals = app.createVertexBuffer(PicoGL.FLOAT, 3, box.normals);
        var uv = app.createVertexBuffer(PicoGL.FLOAT, 2, box.uvs);

        var boxArray = app.createVertexArray()
        .vertexAttributeBuffer(0, positions)
        .vertexAttributeBuffer(1, normals)
        .vertexAttributeBuffer(2, uv);

        var sphere = utils.createSphere();
        var lightPositions = app.createVertexBuffer(PicoGL.FLOAT, 3, sphere.positions);
        var lightIndices = app.createIndexBuffer(PicoGL.UNSIGNED_SHORT, 3, sphere.indices);

        var sphereArray = app.createVertexArray()
        .vertexAttributeBuffer(0, lightPositions)
        .indexBuffer(lightIndices);

        // CAMERA STUFF
        var projMatrix = mat4.create();
        mat4.perspective(projMatrix, Math.PI / 2, canvas.width / canvas.height, 0.1, 10.0);

        var viewMatrix = mat4.create();
        var eyePosition = vec3.fromValues(1, 1, 1);
        mat4.lookAt(viewMatrix, eyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0));

        var viewProjMatrix = mat4.create();
        mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);

        // BOX DESCRIPTIONS FOR GEO PASS
        var boxes = [
            {
                scale: [1, 1, 1],
                rotate: [0, 0, 0],
                translate: [0, 0, 0],
                modelMatrix: mat4.create(),
                mvpMatrix: mat4.create(),
                matrixUniforms: app.createUniformBuffer([
                    PicoGL.FLOAT_MAT4,
                    PicoGL.FLOAT_MAT4
                ]),
                drawCall: null
            },
            {
                scale: [0.1, 0.1, 0.1],
                rotate: [0, 0, Math.PI / 3],
                translate: [0.8, 0.8, 0.4],
                modelMatrix: mat4.create(),
                mvpMatrix: mat4.create(),
                matrixUniforms: app.createUniformBuffer([
                    PicoGL.FLOAT_MAT4,
                    PicoGL.FLOAT_MAT4
                ]),
                drawCall: null
            }
        ];

        for (var i = 0, len = boxes.length; i < len; ++i) {
            boxes[i].drawCall = app.createDrawCall(geoProgram, boxArray)
            .uniformBlock("BoxUniforms", boxes[i].matrixUniforms);
        }

        // LIGHT DESCRIPTIONS FOR DRAW PASS
        var lights = [
            {
                position: vec3.fromValues(0, 1, 0.5),
                color:    vec3.fromValues(0.8, 0.0, 0.0),
                uniforms: null,
                drawCall: null
            },
            {
                position: vec3.fromValues(1, 1, 0.5),
                color:    vec3.fromValues(0.0, 0.0, 0.8),
                uniforms: null,
                drawCall: null
            },
            {
                position: vec3.fromValues(1, 0, 0.5),
                color:    vec3.fromValues(0.0, 0.8, 0.0),
                uniforms: null,
                drawCall: null
            },
            {
                position: vec3.fromValues(0.5, 0, 1),
                color:    vec3.fromValues(0.0, 0.8, 0.8),
                uniforms: null,
                drawCall: null
            }
        ];

        window.onresize = function() {
            app.resize(window.innerWidth, window.innerHeight);
            gBuffer.resize();

            mat4.perspective(projMatrix, Math.PI / 2, app.canvas.width / app.canvas.height, 0.1, 10.0);
            mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);

            for (var i = 0, len = lights.length; i < len; ++i) {
                lightMatrix = mat4.create();
                utils.xformMatrix(lightMatrix, lights[i].position);
                mat4.multiply(lightMatrix, viewProjMatrix, lightMatrix);


                lights[i].uniforms.set(0, lightMatrix).update();
            }
        }

        
        utils.loadImages(["img/webgl-logo.png"], function(images) {
            // CREATE TEXTURE
            var texture = app.createTexture2D(images[0], { flipY: true });
            
            // LIGHT UNIFORMS AND DRAW CALLS    
            var lightMatrix;

            for (var i = 0, len = lights.length; i < len; ++i) {
                lightMatrix = mat4.create();
                utils.xformMatrix(lightMatrix, lights[i].position);
                mat4.multiply(lightMatrix, viewProjMatrix, lightMatrix);

                lights[i].uniforms = app.createUniformBuffer([
                    PicoGL.FLOAT_MAT4,
                    PicoGL.FLOAT_VEC4,
                    PicoGL.FLOAT_VEC4
                ])
                .set(0, lightMatrix)
                .set(1, lights[i].position)
                .set(2, lights[i].color)
                .update();

                lights[i].drawCall = app.createDrawCall(mainProgram, sphereArray)
                .uniformBlock("LightUniforms", lights[i].uniforms)
                .uniform("uEyePosition", eyePosition)
                .texture("uTextureMap", texture)
                .texture("uPositionBuffer", gBuffer.colorAttachments[0])
                .texture("uNormalBuffer", gBuffer.colorAttachments[1])
                .texture("uUVBuffer", gBuffer.colorAttachments[3]);
            }

            function draw() {
                if (timer.ready()) {
                    utils.updateTimerElement(timer.cpuTime, timer.gpuTime);
                }

                timer.start();

                for (var i = 0, len = boxes.length; i < len; ++i) {
                    boxes[i].rotate[0] += 0.01;
                    boxes[i].rotate[1] += 0.02;

                    utils.xformMatrix(boxes[i].modelMatrix, boxes[i].translate, boxes[i].rotate, boxes[i].scale);
                    mat4.multiply(boxes[i].mvpMatrix, viewProjMatrix, boxes[i].modelMatrix);
                
                    boxes[i].matrixUniforms.set(0, boxes[i].mvpMatrix)
                    .set(1, boxes[i].modelMatrix)
                    .update();
                }

                // DRAW TO GBUFFER
                app.drawFramebuffer(gBuffer)
                .depthMask(true)
                .noBlend()
                .clear();

                for (var i = 0, len = boxes.length; i < len; ++i) {
                    boxes[i].drawCall.draw();
                }

                // DRAW LIGHTS
                app.defaultDrawFramebuffer()
                .blend()
                .depthMask(false)
                .clear();

                for (var i = 0, len = lights.length; i < len; ++i) {
                    lights[i].drawCall.draw();
                }
                
                timer.end();                
                
                requestAnimationFrame(draw);
            }

            requestAnimationFrame(draw);
            
        });

    </script>
    <a href="https://github.com/tsherif/picogl.js" id="github-ribbon"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
    <script src="../site/js/iframe.js"></script>
</body>
</html>
